package com.example.onlinemusic.Controller;

import com.example.onlinemusic.Mapper.LoveMusicMapper;
import com.example.onlinemusic.Mapper.MusicMapper;
import com.example.onlinemusic.constants.Constant;
import com.example.onlinemusic.model.Music;
import com.example.onlinemusic.model.Result;
import com.example.onlinemusic.model.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.BindingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.net.BindException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@RequestMapping("/music")
@RestController
public class MusicController {
    @Value("${music.local.path}")
    private String SAVE_PATH;
    @Autowired
    private MusicMapper musicMapper;
    @Autowired
    private LoveMusicMapper loveMusicMapper;

    @RequestMapping("/upload")
    public Result insertMusic(@RequestParam String singer, @RequestParam("filename")
            MultipartFile file, HttpServletRequest request,
                              HttpServletResponse response) {

        //1.检查是否登陆了
        HttpSession session = request.getSession(false);
        System.out.println(session.getAttribute(Constant.USERINFO_SESSION_KEY));
        if (session == null || session.getAttribute(Constant.USERINFO_SESSION_KEY) == null) {
            log.info("没有登陆");
            return Result.fail("请登陆后上传");
        }

        //上传到了服务器
        String fileNameAndType = file.getOriginalFilename();//xxx.mp3
        System.out.println("fileNameAndType :" + fileNameAndType);
        int index = fileNameAndType.lastIndexOf(".");
        String title = fileNameAndType.substring(0, index);
        String path = SAVE_PATH + fileNameAndType;
        //判断上传文件是否是mp3格式
        Music music = musicMapper.findMusicByNameAndBySinger(title);
        //查询数据库中是否有一摸一样的音乐 判断逻辑歌曲名和歌手 如果一致 就不可以
        if (music != null) {
            return Result.fail("歌曲已经存在");
        }
        File dest = new File(path);
        //如果目录不存在创建目录
        if (!dest.exists()) {
            dest.mkdir();
        }
        //上传
        try {
            file.transferTo(dest);
            // return Result.success("上传成功",true);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail("服务器上传失败");
        }
        //进行数据库的上传
        //1.准备数据   2.调用insert
        //找点从后往前找到第一个点
        User user = (User) session.getAttribute(Constant.USERINFO_SESSION_KEY);
        //1.后期播放音乐->http请求
        String url = "/music/get?path=" + title;
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String time = sf.format(new Date());

        try {
            int ret = 0;
            ret = musicMapper.insert(title, singer, time, url, user.getUserId());
            if (ret == 1) {
                response.sendRedirect("/list.html");

                //这里应该跳转到音乐列表页面
                return Result.success("数据库上传成功", ret);
            } else {
                return Result.fail("数据库上传失败");
            }
        } catch (BindingException | IOException e) {
            dest.delete();
            return Result.fail("数据库上传失败");

        }

    }

    /***
     * 播放音乐的时候 /music/get?path=xxx.mp3
     * @param path
     * @return
     */
    @RequestMapping("/get")
    public ResponseEntity<byte[]> get(String path) {
        try {
            //找到目录下的文件并解析
            byte[] bytes = Files.readAllBytes(new File(SAVE_PATH + path).toPath());
            System.out.println(ResponseEntity.ok(bytes).getBody());
            return ResponseEntity.ok(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /***
     * 删除单个音乐
     * @param musicId
     * @return
     */
    @RequestMapping("/delete")
    public Result deleteMusicByMusicId(@RequestParam("musicId") String musicId) {
        //1.先检查音乐是否存在
        int musicId1 = Integer.parseInt(musicId);
        Music music = musicMapper.findMusicByMusicId(musicId1);

        //2.如果存在进行删除
        if (music == null) {
            return Result.fail("没有你要删除的音乐");
        } else {
            //2.1删除数据库
            int ret = musicMapper.deleteMusicByMusicId(musicId1);
            if (ret == 1) {
                //2.2删除服务器上的数据
                //获取文件名
                int index = music.getUrl().lastIndexOf("=");
                String s = music.getUrl().substring(index + 1);
                File file = new File(SAVE_PATH + s + ".mp3");
                System.out.println("当前的路径：" + file.getPath());
                if (file.delete()) {
                    //同步删除love表中的音乐
                    loveMusicMapper.deleteLoveMusicByMusicId(musicId1);
                    return Result.success("服务器删除音乐成功", 1);
                } else {
                    return Result.fail("服务器音乐删除失败");
                }
            } else {
                return Result.fail("数据库中的音乐删除失败");
            }
        }

    }

    /***
     * 批量删除
     * @param listId
     * @return
     */
    @RequestMapping("/deleteSel")
    public Result deleteSelMusic(@RequestParam("musicIds[]") List<Integer> listId) {
        log.info("所以的Id{}", listId.toString());

        int sum = 0;
        for (int i = 0; i < listId.size(); i++) {
            int musicId = listId.get(i);
            Music music = musicMapper.findMusicByMusicId(musicId);

            //2.如果存在进行删除
            if (music == null) {
                log.info("没有这个Id{}的音乐", musicId);
                return Result.fail("没有你要删除的音乐");
            } else {
                //2.1删除数据库
                int ret = musicMapper.deleteMusicByMusicId(musicId);
                if (ret == 1) {
                    //2.2删除服务器上的数据
                    //获取文件名
                    int index = music.getUrl().lastIndexOf("=");
                    String s = music.getUrl().substring(index + 1);
                    File file = new File(SAVE_PATH + s + ".mp3");
                    System.out.println("当前的路径：" + file.getPath());
                    if (file.delete()) {
                        loveMusicMapper.deleteLoveMusicByMusicId(musicId);
                        sum += ret;
                    } else {
                        return Result.fail("服务器音乐删除失败");
                    }
                } else {
                    return Result.fail("数据库中的音乐删除失败");
                }
            }
        }

        if (sum == listId.size()) {
            log.info("整体删除成功！");

            return Result.success("音乐删除成功", sum);
        } else {
            log.info("整体删除失败！");
            return Result.fail("音乐删除失败");
        }

    }

    /***
     * 搜索音乐
     * @param musicName 参数可能为空
     * @return
     */
    @RequestMapping("/findMusic")
    public Result findMusic(@RequestParam(required = false) String musicName) {
        System.out.println(musicName);
        List<Music> musicList = null;
        if (musicName != null) {
            musicList = musicMapper.findMusicByName(musicName);

        } else {
            musicList = musicMapper.findMusic();

        }
        return Result.success("查询到了所有的音乐", musicList);
    }

}
